package com.linjj.seckill.exception;

import com.linjj.seckill.vo.CodeMsg;
import com.linjj.seckill.vo.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 全局异常处理器
 * 作用：拦截异常并处理
 * */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandle(HttpServletRequest request,Exception e){
        if(e instanceof BindException){
            BindException be = (BindException) e;
            List<ObjectError> errors = be.getAllErrors();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(errors.get(0).getDefaultMessage()));
        }
        if(e instanceof GlobalException){
            GlobalException ge = (GlobalException) e;
            return Result.error(ge.getCm());
        }
        else{
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
